package com.twosnail.frame.model;

import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.twosnail.frame.commin.exception.BuziException;
import com.twosnail.frame.commin.util.message.SendMessage;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * Created by yangcs on 2017/7/20.
 */
@SuppressWarnings("serial")
public class IdentifyingCode extends Model<IdentifyingCode> {
    private Logger logger = Logger.getLogger(IdentifyingCode.class) ;
    public static final IdentifyingCode me = new IdentifyingCode() ;

    private static final String[] CODE = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","P","Q","R",
            "S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};

    /**
     * 获取登录用户下所有健身劵使用记录
     */
    public Page<Record> getAllCode( int pageNumber, int pageSize,String  keyWord){
        StringBuffer sb = new StringBuffer(" FROM identifying_code a LEFT JOIN wx_user b ON a.wxUserId = b.wxUserId ");
        if( keyWord != null && !"".equals( keyWord = keyWord.trim() ) ) {
            sb.append( " where (a.code LIKE '%"+keyWord+"%' or b.mobile LIKE '%"+keyWord+"%')" ) ;
        }
        sb.append(" order by b.mobile desc");
        return Db.paginate(pageNumber, pageSize,
                "SELECT a.`code`, a.state, FROM_UNIXTIME( a.useTime / 1000, '%Y-%m-%d %H:%i:%S' ) useTime, FROM_UNIXTIME( a.createTime / 1000, '%Y-%m-%d %H:%i:%S' ) createTime," +
                        " FROM_UNIXTIME( a.expTime / 1000, '%Y-%m-%d %H:%i:%S' ) expTime, a.count, b.mobile  " , sb.toString() );
    }

    public void addCodes(long wxUserId,int count,String mobile,String days){
        long createTime = System.currentTimeMillis();
        long expTime;
        if( days == null || "".equals(days.trim()) ){
            expTime = getOneYear(createTime);
        }else{
            expTime = getTimeLongs(days+" 23:59:59");
        }
        IdentifyingCode identifyingCode = new IdentifyingCode();
        identifyingCode.set("wxUserId",wxUserId);
        identifyingCode.set("state",1);
        identifyingCode.set("createTime",createTime);
        identifyingCode.set("count",count);
        identifyingCode.set("expTime",expTime);
        identifyingCode.set("code",getCode());
        add(identifyingCode);
        SendMessage.send(mobile,identifyingCode.getStr("code"));
    }

    public void addVip(long wxUserId,String mobile){
        long createTime = System.currentTimeMillis();
        long expTime = getOneYear(createTime);
        IdentifyingCode identifyingCode = new IdentifyingCode();
        identifyingCode.set("wxUserId",wxUserId);
        identifyingCode.set("state",1);
        identifyingCode.set("createTime",createTime);
        identifyingCode.set("count",0);
        identifyingCode.set("expTime",expTime);
        identifyingCode.set("code",getCode());
        add(identifyingCode);
        SendMessage.send1(mobile,identifyingCode.getStr("code"));
    }

    public long getOneYear(long now){
        Calendar calendar = Calendar.getInstance();
        Date date = new Date(now);
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1);
        return calendar.getTimeInMillis();
    }

    public static long getTimeLongs(String user_time) {
        long date;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d;
        try {
            d = sdf.parse(user_time);
            date = d.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            return System.currentTimeMillis();
        }
        return date;
    }

    public String add(IdentifyingCode identifyingCode){
        String code;
        try {
            code = addCode(identifyingCode);
        }catch (Exception e){
            logger.info("生成代金劵出错");
            code = add(identifyingCode);
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 添加菜单信息
     * @param identifyingCode
     * @throws BuziException
     */
    public String addCode( IdentifyingCode identifyingCode) throws BuziException {
        if( !identifyingCode.save() ) {
            throw new BuziException( "添加代金劵失败!" );
        }
        return identifyingCode.getStr("code") ;
    }

    private static String getCode(){
        int a;
        StringBuffer sb = new StringBuffer();
        for (int j=0;j<6;j++){
            a = Math.abs((new Random()).nextInt(34));// 产生0~57的随机数
            sb.append(CODE[a]);
        }
        return sb.toString();
    }

    /**
     * 过期验证码无效
     */
    public void refund(){
        Db.update("UPDATE identifying_code g SET g.state = 3 where expTime < "+System.currentTimeMillis());
    }
}
